package cc.aiee.core.kit;

import javax.servlet.http.HttpServletRequest;

import cc.aiee.core.pojo.vo.IpVO;

public class KitIp {

	/**
	 * 通过代理服务器 获取真实的ip地址
	 * 
	 * <li>Nginx 配置:</li>
	 * <li>proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	 * 每经过一个代理服务器,则添加代理服务器的ip</li>
	 * <li>proxy_set_header X-Real-IP $remote_addr; 客户端真实的IP</li>
	 * 
	 * @param request
	 * @return
	 * @author YangLong <br>
	 *         2020-09-30 09:46:42
	 */
	public static String getRealIp(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		// 对于通过多个代理的情况，第一个 IP 为客户端真实 IP，多个IP按照','分割
		if (ip != null && ip.length() > 15) {
			if (ip.indexOf(",") > 0) {
				ip = ip.substring(0, ip.indexOf(","));
			}
		}
		return ip;
	}

	/**
	 * 获取真实的ip地址,(非代理服务器转)
	 * 
	 * @param request
	 * @return
	 * @author YangLong <br>
	 *         2020-09-30 09:41:02
	 */
	public static String getRealIpByNotPorxy(HttpServletRequest request) {
		String accessIp = request.getHeader("X-Forwarded-For");
		return null == accessIp ? request.getRemoteAddr() : accessIp;
	}

	public static IpVO show(HttpServletRequest request) {
		IpVO ip = new IpVO();
		ip.setHeader_x_forwarded_for(request.getHeader("X-Forwarded-For"));
		ip.setHeader_WL_Proxy_Client_IP(request.getHeader("WL-Proxy-Client-IP"));
		ip.setRequest_remoteAddr(request.getRemoteAddr());
		ip.setHeader_Proxy_Client_IP(request.getHeader("Proxy-Client-IP"));
		ip.setHeader_X_Real_IP(request.getHeader("X-Real-IP"));
		return ip;
	}
}
